package people.paper.tv.activity.home.modual.sptt.view.impl;

import android.content.Context;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v7.widget.NewRecycleAdapter;
import android.support.v7.widget.NewRecyclerView;
import android.support.v7.widget.OrientationHelper;
import android.util.Log;
import android.util.SparseArray;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;

import com.skyworth.ui.api.SkyWithBGLoadingView;
import com.skyworth.ui.newrecycleview.NewRecycleAdapterItem;
import com.skyworth.ui.newrecycleview.NewRecycleLayout;
import com.skyworth.ui.newrecycleview.OnBoundaryListener;
import com.skyworth.ui.newrecycleview.OnItemClickListener;
import com.skyworth.ui.newrecycleview.OnItemFocusChangeListener;
import com.skyworth.ui.newrecycleview.OnScrollStateListener;
import com.skyworth.util.UiCompat;
import com.skyworth.util.Util;

import java.util.ArrayList;
import java.util.List;

import people.paper.tv.R;
import people.paper.tv.activity.home.HomeActivity;
import people.paper.tv.activity.home.modual.sptt.view.data.VideoData;
import people.paper.tv.activity.home.modual.ywyl.view.impl.IViewCallBack;
import people.paper.tv.utils.ui.Common;
import people.paper.tv.utils.ui.ServerErrorLayout;

public class HeadlineListView extends FrameLayout implements OnBoundaryListener,
        OnScrollStateListener, OnItemFocusChangeListener, OnItemClickListener {
    final String TAG = "YWYLViewImpl";
    NewRecycleLayout gridView;
    List<VideoData> gridDatas;
    NewRecycleAdapter gridAdapter;
    int curPage = -1;
    ISPTTViewCallBack viewCallBack;
    SparseArray<List<VideoData>> newsSparse;
    int curPosition = 0;
    SkyWithBGLoadingView loadingView;
    boolean fullMode = false;
    HeadlineLayout parentLayout;

    public HeadlineListView(@NonNull Context context) {
        super(context);
        setClipChildren(false);
        setClipToPadding(false);
        showLoading();
        setBackgroundColor(getResources().getColor(R.color.video_bg));
        newsSparse = new SparseArray<>();
    }

    private void createNewsList(){
        gridView = new NewRecycleLayout(getContext(), 1, OrientationHelper.VERTICAL);
        FrameLayout.LayoutParams gridViewParams = new FrameLayout.LayoutParams(Util.Div(636), Util.Div(840));
        gridView.setItemSpace(Util.Div(0),Util.Div(0));
        addView(gridView,gridViewParams);
        gridView.setBackgroundColor(getResources().getColor(R.color.video_list_bg));
        gridView.setMiddleScroll(true);
        gridView.setmBoundaryListener(this);
        gridView.setmScrollStateListener(this);
        gridView.setmItemFocusChangeListener(this);
        gridView.setmItemClickListener(this);
        gridView.setClipChildren(false);
        gridView.setClipToPadding(false);
    }

    public void setParentViewCallback(ISPTTViewCallBack view){
        viewCallBack = view;
    }

    public void setParentLayout(HeadlineLayout l){
        parentLayout = l;
    }

    public void setMode(boolean mode){
        fullMode = mode;
        if(fullMode){
            gridView.setBackground(null);
        }else {
            gridView.setBackgroundColor(getResources().getColor(R.color.video_list_bg));
        }
    }

    public void refresh(int pageIndex, List<VideoData> datas){
        if(datas == null || datas.size() == 0) {
            curPage = -1;
        }else {
            if(pageIndex == 0)
                hideLoading();
            curPage = pageIndex;
            newsSparse.put(curPage, datas);
            if(gridView == null) {
                createNewsList();
            }
            if(gridDatas == null){
                setAdapter(datas);
            }else {
                updateUI(datas);
            }
        }
    }

    protected void setAdapter(List<VideoData> datas){
        if(datas == null || datas.size() <= 0)
            return;
        gridDatas = new ArrayList<>();
        int size = datas.size();
        for(int i = 0; i < size; i++)
        {
            gridDatas.add(datas.get(i));
        }
        gridAdapter = new NewRecycleAdapter<VideoData>(gridDatas,1) {
            @Override
            public NewRecycleAdapterItem<VideoData> onCreateItem(Object type) {
                return new HeadlineItemView(getContext());
            }
        };
        gridView.setRecyclerAdapter(gridAdapter);
        gridView.post(new Runnable() {
            @Override
            public void run() {
                if(fullMode){
                    if(gridDatas.size() > curPosition){
                        View view = gridView.getViewByPosition(curPosition);
                        if(view != null){
                            gridView.scrollToPosition(curPosition);
                            view.requestFocus();
                        }
                    }
                }else {
                    if(Common.CurTab == HomeActivity.SPTT_INDEX)
                        if(gridView.getViewByPosition(0) != null) {
                            //播放第一个
                            gridDatas.get(0).onPlay.run();
                        }
                }

            }
        });
    }

    public boolean getFocus(){
        if(gridDatas.size() > curPosition){
            View view = gridView.getViewByPosition(curPosition);
            if(view != null){
                view.requestFocus();
                return true;
            }
        }
        return false;
    }

    public boolean changeFocus() {
        if(gridView != null && gridView.getChildItemCount() > 0){
            View view = gridView.getViewByPosition(gridView.getFirstVisiblePosition());
            if(view != null){
                view.requestFocus();
                return true;
            }
        }else{
            if(serverErrorLayout != null && serverErrorLayout.getVisibility() == VISIBLE){
                serverErrorLayout.setFocus();
                return true;
            }
        }
        return false;
    }

    public void updateUI( List<VideoData> newItems) {
        int startPosition = gridDatas.size();
        gridDatas.addAll(newItems);
        if (gridView != null) {
            int itemCount = gridDatas.size();
            gridView.notifyItemRangeInserted(startPosition, itemCount);
        }
    }

    public int getTotal(){
        if(gridDatas == null)
            return 0;
        return gridDatas.size();
    }

    public void showLoading() {
        if (loadingView == null) {
            loadingView = new SkyWithBGLoadingView(getContext());
            LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT, Gravity.CENTER_VERTICAL);
            params.leftMargin = Util.Div(153);
            addView(loadingView, params);
        }
        loadingView.setVisibility(View.VISIBLE);
        loadingView.showLoading();
        loadingView.bringToFront();
        if (loadingView.getParent() != null)
            loadingView.getParent().requestLayout();
    }

    public void hideLoading() {
        if (loadingView != null) {
            loadingView.dismissLoading();
            removeView(loadingView);
            loadingView = null;
        }
    }

    @Override
    public boolean onLeftBoundary(View view, int i) {
        if(!fullMode)
            viewCallBack.preFragment();
        return true;
    }

    @Override
    public boolean onTopBoundary(View view, int i) {
        if(!fullMode)
            viewCallBack.changeFocus();
        return true;
    }

    @Override
    public boolean onDownBoundary(View view, int i) {
        return true;
    }

    @Override
    public boolean onRightBoundary(View view, int i) {
        if(!fullMode)
            ((HeadlineLayout)viewCallBack.getParentView()).setVideoFocus();
        return true;
    }

    @Override
    public boolean onOtherKeyEvent(View view, int i, int i1) {
        if(fullMode)
            return parentLayout.onKey(view, i1, new KeyEvent(KeyEvent.ACTION_DOWN, i1));
        else
            return false;
    }

    @Override
    public void onScrollby(int i) {

    }

    @Override
    public void onScrollStart() {

    }

    @Override
    public void onScrollEnd(NewRecyclerView newRecyclerView, int i, int i1) {
        Log.i("onNewsLoad", "SPTTViewImpl onScrollEnd UiDataHandler:"+curPage+"; "+i1);
        if(!fullMode)
            if (curPage >= 0 && newsSparse.get(curPage+1) == null) {
                viewCallBack.getNextPageData(curPage);
            }
    }

    public void refreshCurPlayId(int position){
        Log.i("SPTTViewImpl onNewsLoad", "SPTTViewImpl refreshCurPlayId:" + position
                +"; "+curPosition+"; "+gridView.getChildItemCount());
        gridDatas.get(curPosition).isCurSelected = false;
        gridDatas.get(position).isCurSelected = true;
        gridView.notifyItemChanged(curPosition);
        gridView.notifyItemChanged(position);
        int oldPos = curPosition;
        curPosition = position;
        setPlay(true, oldPos);
        gridView.smoothScrollToPosition(position);
    }

    public void setPlay(boolean isPlay, int oldPos){
        if(gridDatas == null || gridDatas.size() == 0 || gridView == null)
            return;
        if(oldPos >= 0){
            gridDatas.get(oldPos).isCurPlay = false;
            gridView.notifyItemChanged(oldPos);
        }
        gridDatas.get(curPosition).isCurPlay = isPlay;
        gridView.notifyItemChanged(curPosition);
    }

    @Override
    public void focusChange(View view, int i, boolean hasFocus) {
        HeadlineItemView itemView = (HeadlineItemView)view;
        itemView.onFocusChange(hasFocus);
    }

    @Override
    public void click(View v, int position) {
        HeadlineItemView itemView = (HeadlineItemView)v;
        itemView.onClickAction();
    }

    ServerErrorLayout serverErrorLayout;
    public void showError() {
        if(curPage >= 0)
            return;
        if (serverErrorLayout == null) {
            serverErrorLayout = new ServerErrorLayout(getContext(), reloadCallback);
            LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT, Gravity.CENTER_VERTICAL);
            params.leftMargin = Util.Div(153);
            addView(serverErrorLayout, params);
        }
        serverErrorLayout.setVisibility(View.VISIBLE);
        serverErrorLayout.bringToFront();
        if (serverErrorLayout.getParent() != null)
            serverErrorLayout.getParent().requestLayout();
    }

    public void hideError() {
        if (serverErrorLayout != null) {
            removeView(serverErrorLayout);
            serverErrorLayout = null;
        }
    }

    ServerErrorLayout.ReloadCallback reloadCallback = new ServerErrorLayout.ReloadCallback() {
        @Override
        public void reload() {
            viewCallBack.changeFocus();
            hideError();
            showLoading();
            viewCallBack.getNextPageData(-1);
        }

        @Override
        public boolean onkeyListener(View v, int keyCode, KeyEvent event) {
            if(event.getAction() == KeyEvent.ACTION_DOWN){
                if(keyCode == KeyEvent.KEYCODE_DPAD_LEFT){
                    viewCallBack.preFragment();
                    return true;
                }else if(keyCode == KeyEvent.KEYCODE_DPAD_RIGHT){
                    ((HeadlineLayout)viewCallBack.getParentView()).setVideoFocus();
                    return true;
                }else if(keyCode == KeyEvent.KEYCODE_DPAD_UP){
                    viewCallBack.changeFocus();
                    return true;
                }else if(keyCode == KeyEvent.KEYCODE_DPAD_DOWN){
                    return true;
                }
            }
            return false;
        }
    };
}
